home *** CD-ROM | disk | FTP | other *** search
/ Super PC 34 / Super PC 34 (Shareware).iso / spc / UTIL / DJGPP2 / V2 / DJLSR200.ZIP / src / libc / posix / sys / stat / stat.c < prev    next >
Encoding:
C/C++ Source or Header  |  1996-01-24  |  31.1 KB  |  832 lines

  1. /* Copyright (C) 1996 DJ Delorie, see COPYING.DJ for details */
  2. /* Copyright (C) 1995 DJ Delorie, see COPYING.DJ for details */
  3. /* This is file STAT.C */
  4. /*
  5.  *   Almost a 100% U**X-compatible stat() substitute.
  6.  *
  7.  * Usage:
  8.  *
  9.  *   That's easy: put this into libc.a, then just call stat() as usual.
  10.  *
  11.  * Rationale:
  12.  *
  13.  *   Many Unix-born programs make heavy use of stat() library
  14.  *   function to make decisions on files' equality, size, access
  15.  *   attributes etc.  In the MS-DOS environment, many implementations
  16.  *   of stat() are crippled, because DOS makes it very hard to get to
  17.  *   certain pieces of information about files and directories.  Thus
  18.  *   porting a program to DOS is usually an exercise in #ifdef'ing.
  19.  *   This implementation facilitates porting Unix programs to MS-DOS
  20.  *   by providing stat() which is much more Unix-compatible than those
  21.  *   of most DOS-based C compilers (e.g., Borland's).
  22.  *   Specifically, the following issues are taken care of:
  23.  *
  24.  *      1. This stat() doesn't fail for root directories, returning
  25.  *         valid information.
  26.  *      2. Directory size is not reported zero; the number of used
  27.  *         directory entries multiplied by entry size is returned instead.
  28.  *      3. Mode bits are set for all 3 groups (user, group, other).
  29.  *      4. Directories are NOT reported read-only, unless one of R, H or S
  30.  *         attributes is set.
  31.  *      5. Directories have their execute bit set, as they do under Unix.
  32.  *      6. Device names (such as /dev/con, lpt1, aux etc.) are treated as
  33.  *         if they were on a special drive called `@:' (st_dev = -1).
  34.  *         The "character special" mode bit is set for these devices.
  35.  *      7. The inode number (st_ino) is taken from the starting cluster
  36.  *         number of the file.  If the cluster number is unavailable, it
  37.  *         is invented using the file's name in a manner that minimizes
  38.  *         the possibility of inventing an inode which already belongs
  39.  *         to another file.  See below for details.
  40.  *      8. Executable files are found based on files' extensions and
  41.  *         magic numbers present at their beginning, and their execute
  42.  *         bits are set.
  43.  *
  44.  *   Lossage:
  45.  *
  46.  *      Beautiful as the above sounds, this implementation does fail
  47.  *      under certain circumstances.  The following is a list of known
  48.  *      problems:
  49.  *
  50.  *      1. The time fields for a root directory cannot be obtained, so
  51.  *         they are set to the beginning of the Epoch.
  52.  *      2. For files which reside on networked drives, the inode number
  53.  *         is invented, because network redirectors usually do not
  54.  *         bring that info with them.  This is not a total lossage, but
  55.  *         it could get us a different inode for each program run.
  56.  *      3. Empty files do not have a starting cluster number, because
  57.  *         DOS doesn't allocate one until you actually write something
  58.  *         to a file.  For these the inode is also invented.
  59.  *      4. If the st_ino field is a 16 bit number, the invented inode
  60.  *         numbers are from 65535 and down, assuming that most disks have
  61.  *         unused portions near their end.  Valid cluster numbers are 16-bit
  62.  *         unsigned integers, so a possibility of a clash exists, although
  63.  *         the last 80 or more cluster numbers are unused on all drives
  64.  *         I've seen.  If the st_ino is 32 bit, then invented inodes are
  65.  *         all greater than 64k, which totally eliminates a possibility
  66.  *         of a clash with an actual cluster number.
  67.  *      5. The method of computing directory size is an approximation:
  68.  *         a directory might consume much more space, if it has many
  69.  *         deleted entries.  Still, this is a close approximation, and
  70.  *         it does follow the logic of reporting size for a regular file:
  71.  *         only the actually used space is returned.
  72.  *      6. As this implementation relies heavily on undocumented DOS
  73.  *         features, it will fail to get actual file info in environments
  74.  *         other than native DOS, such as DR-DOS, OS/2 etc.  For these,
  75.  *         the function will return whatever info is available with
  76.  *         conventional DOS calls, which is no less than any other
  77.  *         implementation could do.  This stat() might also fail for
  78.  *         future DOS versions, if the layout of internal DOS data
  79.  *         area is changed; however, this seems unlikely.
  80.  *
  81.  * Copyright (c) 1994-96 Eli Zaretskii <eliz@is.elta.co.il>
  82.  *
  83.  * This software may be used freely so long as this copyright notice is
  84.  * left intact.  There is no warranty on this software.
  85.  *
  86.  */
  87.  
  88. /*
  89.  * Tested with DJGPP port of GNU C compiler, versions 1.11maint5 and 1.12,
  90.  * under MS-DOS 3.3, 4.01, 5.0, 6.20 (with and without DoubleSpace) and
  91.  * with networked drives under XFS 1.86, Novell Netware 3.22, and
  92.  * TSoft NFS 0.24Beta.
  93.  *
  94.  */
  95.  
  96. #include <libc/stubs.h>
  97. #include <stdlib.h>
  98. #include <stddef.h>
  99. #include <unistd.h>
  100. #include <time.h>
  101. #include <stdio.h>
  102. #include <string.h>
  103. #include <ctype.h>
  104. #include <errno.h>
  105. #include <fcntl.h>
  106. #include <sys/types.h>
  107. #include <sys/stat.h>
  108. #include <dos.h>
  109. #include <dir.h>
  110.  
  111. #include <dpmi.h>
  112. #include <go32.h>
  113. #include <libc/farptrgs.h>
  114. #include <libc/bss.h>
  115.  
  116. #include "xstat.h"
  117.  
  118. int __getdisk(void);
  119. int __findfirst(const char *, struct ffblk *, int);
  120. int __findnext(struct ffblk *);
  121.  
  122. #define ALL_FILES   (FA_RDONLY|FA_HIDDEN|FA_SYSTEM|FA_DIREC|FA_ARCH)
  123.  
  124. #define _STAT_INODE         1   /* should we bother getting inode numbers? */
  125. #define _STAT_EXEC_EXT      2   /* get execute bits from file extension? */
  126. #define _STAT_EXEC_MAGIC    4   /* get execute bits from magic signature? */
  127. #define _STAT_DIRSIZE       8   /* compute directory size? */
  128. #define _STAT_ROOT_TIME  0x10   /* try to get root dir time stamp? */
  129. #define _STAT_WRITEBIT   0x20   /* fstat() needs write bit? */
  130.  
  131. /* Should we bother about executables at all? */
  132. #define _STAT_EXECBIT       (_STAT_EXEC_EXT | _STAT_EXEC_MAGIC)
  133.  
  134. /* The structure of the full directory entry.  This is the 32-byte
  135.    record present for each file/subdirectory in a DOS directory.
  136.    Although the ``packed'' attribute seems to be unnecessary, I use
  137.    it to be sure it will still work for future versions of GCC.  */
  138.  
  139. struct full_dirent {
  140.   char           fname[8]      __attribute__ ((packed));
  141.   char           fext[3]       __attribute__ ((packed));
  142.   unsigned char  fattr         __attribute__ ((packed));
  143.   unsigned char  freserved[10] __attribute__ ((packed));
  144.   unsigned short ftime         __attribute__ ((packed));
  145.   unsigned short fdate         __attribute__ ((packed));
  146.   unsigned short fcluster      __attribute__ ((packed));
  147.   unsigned int   fsize         __attribute__ ((packed));
  148. };
  149.  
  150.  
  151. /* Static variables to speed up SDA DOS Swappable Data Area access on
  152.    subsequent calls.  */
  153.  
  154. /* The count of number of SDA's we have.  It is more than 1 for DOS
  155.    4.x only.  If it has a value of 0, the function init_dirent_table()
  156.    will be called to compute the addresses where we are to look for
  157.    directory entry of our file.  A value of -1 means this method is
  158.    unsupported for this version of DOS.  */
  159. static int  dirent_count;
  160.  
  161. /* The table of places to look for our directory entry.
  162.    Each entry in the table is a linear offset from the beginning of
  163.    conventional memory which points to a particular location within
  164.    one of the SDA's, where the entry of a file being stat()'ed could
  165.    appear.  The offsets are computed once (when the routine is first
  166.    called) and then reused for other calls.  The actual storage for
  167.    the table is malloc()'ed when this function is first called.  */
  168. static unsigned int * dirent_table;
  169.  
  170. /* When we have only one SDA, this is where its only place to look for
  171.    directory entry is stored.  */
  172. static unsigned int   dirent_place;
  173.  
  174. /* This holds the fail bits from the last call to init_dirent_table(),
  175.    so we can return them every time get_inode_from_sda() is called.  */
  176. static unsigned short init_dirent_table_bits;
  177.  
  178. /* Holds the last seen value of __bss_count, to be safe for
  179.    restarted programs (emacs).  */
  180. static int stat_count = -1;
  181.  
  182. /*
  183.  * Parts of the following code is derived from file DOSSWAP.C,
  184.  * which came with ``Undocumented DOS'', 1st edition.
  185.  */
  186.  
  187. /* Compute table of pointers to look for directory entry of a file.  */
  188. static int
  189. init_dirent_table (void)
  190. {
  191.   short          get_sda_func;
  192.   unsigned short dirent_offset;
  193.   unsigned short true_dos_version;
  194.   unsigned short dos_major, dos_minor;
  195.   __dpmi_regs    regs;
  196.  
  197.   if (dirent_count == -1)     /* we already tried and found we can't */
  198.     return 0;
  199.  
  200.   /* Compute INT 21h function number and offset of directory entry
  201.      from start of SDA.  These depend on the DOS version.
  202.      We need exact knowledge about DOS internals, so we need the
  203.      TRUE DOS version (not the simulated one by SETVER), if that's
  204.      available.  */
  205.   true_dos_version = _get_dos_version(1);
  206.   dos_major = true_dos_version >> 8;
  207.   dos_minor = true_dos_version & 0xff;
  208.  
  209.   if ((dos_major == 3) && (dos_minor >= 10))
  210.     {
  211.       get_sda_func  = 0x5d06;
  212.       dirent_offset = 0x1a7;
  213.     }
  214.   else if (dos_major == 4)
  215.     {
  216.       /* According to ``Undocumented DOS, 2nd edition'', I could have
  217.          used 5d06 here, as for DOS 5 and above, but I like to be
  218.          defensive.  In fact, the above book itself uses 5d0b, contrary
  219.          to its own recommendation.  */
  220.       get_sda_func  = 0x5d0b;
  221.       dirent_offset = 0x1b3;
  222.     }
  223.   else if (dos_major >= 5)
  224.     {
  225.       get_sda_func  = 0x5d06;
  226.       dirent_offset = 0x1b3;
  227.     }
  228.   else
  229.     {
  230.       _djstat_fail_bits |= _STFAIL_OSVER;
  231.       dirent_count = -1;
  232.       return 0;
  233.     }
  234.  
  235.   _djstat_fail_bits &= ~_STFAIL_OSVER;  /* version is OK */
  236.  
  237.   /* Get the pointer to SDA by calling undocumented function 5dh of INT 21. */
  238.   regs.x.ax = get_sda_func;
  239.   __dpmi_int(0x21, ®s);
  240.   if (regs.x.flags & 1)
  241.     {
  242.       _djstat_fail_bits |= _STFAIL_SDA;
  243.       dirent_count = -1;      /* if the call failed, never try this later */
  244.       return 0;
  245.     }
  246.  
  247.   _djstat_fail_bits &= ~_STFAIL_SDA;    /* Get SDA succeeded */
  248.  
  249.   /* DOS 4.x might have several SDA's, which means we might have more
  250.      than one place to look into.  (It is typical of DOS 4 to complicate
  251.      things.)
  252.      Compute all the possible addresses where we will have to look.  */
  253.   if (dos_major == 4)
  254.     {
  255.       /* The pointer returned by INT 21h, AX=5D0b points to a header
  256.          which holds a number of SDA's and then an array of that number
  257.          of records each one of which includes address of an SDA (DWORD)
  258.          and its length and type (encoded in a WORD).
  259.          While walking this list of SDA's, we add to each pointer the
  260.          offset of directory entry and stash the resulting address in
  261.          our table for later use.  */
  262.  
  263.       int  sda_list_walker = MK_FOFF(regs.x.ds, regs.x.si);
  264.       int  i;
  265.       int *tbl;
  266.  
  267.       dirent_count = _farpeekw(_dos_ds, sda_list_walker); /* number of SDA's */
  268.  
  269.       /* Allocate storage for table.  */
  270.       tbl = dirent_table = (int *)malloc(dirent_count*sizeof(int));
  271.       if (!dirent_table)
  272.         {
  273.           /* If malloc() failed, maybe later it will succeed, so don't
  274.              store -1 in dirent_count.  */
  275.           dirent_count = 0;
  276.           _djstat_fail_bits |= _STFAIL_DCOUNT;
  277.           return 0;
  278.         }
  279.  
  280.       memset(dirent_table, 0, dirent_count*sizeof(int));
  281.       _djstat_fail_bits &= ~_STFAIL_DCOUNT; /* dirent_count seems OK */
  282.  
  283.       /* Walk the array of pointers, computing addresses of directory
  284.          entries and stashing them in our table.  */
  285.       _farsetsel(_dos_ds);
  286.       for (i = dirent_count, sda_list_walker += 2; i--; sda_list_walker += 6)
  287.         {
  288.           int            sda_start = _farnspeekl(sda_list_walker);
  289.           unsigned short sda_len   = _farnspeekw(sda_list_walker + 4) & 0x7fff;
  290.  
  291.           /* Let's be defensive here: if this SDA is too short to have
  292.              place for directory entry, we won't use it.  */
  293.           if (sda_len > dirent_offset)
  294.             *tbl++ = sda_start + dirent_offset;
  295.           else
  296.             dirent_count--;
  297.         }
  298.     }
  299.  
  300.   /* DOS 3.1 and 5.0 or later.  We have only one SDA pointed to by
  301.      whatever INT 21h, AH=5d returns.  */
  302.   else
  303.     {
  304.       dirent_count = 1;
  305.       dirent_place = MK_FOFF(regs.x.ds, regs.x.si) + dirent_offset;
  306.       dirent_table = &dirent_place;
  307.     }
  308.  
  309.   return 1;
  310. }
  311.  
  312. /* Get inode number by searching DOS Swappable Data Area.
  313.    The entire directory entry for a file found by FindFirst/FindNext
  314.    appears at a certain (version-dependent) offset in the SDA after
  315.    one of those function is called.
  316.    Should be called immediately after calling DOS FindFirst function,
  317.    before the info is overwritten by somebody who calls it again.  */
  318. static unsigned int
  319. get_inode_from_sda(const char *basename)
  320. {
  321.   int            count          = dirent_count;
  322.   unsigned int * dirent_p       = dirent_table;
  323.   unsigned short dos_mem_base   = _dos_ds;
  324.   unsigned short our_mem_base   = _my_ds();
  325.   char  * dot                   = strchr(basename, '.');
  326.   size_t  total_len             = strlen(basename);
  327.   int     name_len              = dot ? dot - basename : total_len;
  328.   int     ext_len               = dot ? total_len - name_len - 1 : 0;
  329.   int     cluster_offset        = offsetof(struct full_dirent, fcluster);
  330.  
  331.   /* Restore failure bits set by last call to init_dirent_table(), so
  332.      they will be reported as if it were called now.  */
  333.   _djstat_fail_bits = init_dirent_table_bits;
  334.  
  335.   /* Force reinitialization in restarted programs (emacs).  */
  336.   if (stat_count != __bss_count)
  337.     {
  338.       stat_count = __bss_count;
  339.       dirent_count = 0;
  340.     }
  341.  
  342.   /* Initialize the table of SDA entries where we are to look for
  343.      our file.  */
  344.   if (!dirent_count && !init_dirent_table())
  345.     {
  346.       init_dirent_table_bits = _djstat_fail_bits;
  347.       return 0;
  348.     }
  349.   init_dirent_table_bits = _djstat_fail_bits;
  350.   if (dirent_count == -1)
  351.     return 0;
  352.  
  353.   count = dirent_count;
  354.   dirent_p = dirent_table;
  355.  
  356.   _farsetsel(dos_mem_base);
  357.  
  358.   /* This is DOS 4.x lossage: this loop might execute many times.
  359.      For other DOS versions it is executed exactly once.  */
  360.   while (count--)
  361.     {
  362.       unsigned int  src_address = *dirent_p & 0x000fffff;
  363.       char          cmp_buf[sizeof(struct full_dirent)];
  364.  
  365.       /* Copy the directory entry from the SDA to local storage.
  366.          The filename is stored there in infamous DOS format: name and
  367.          extension blank-padded to 8/3 characters, no dot between them.  */
  368.       movedata(dos_mem_base, src_address, our_mem_base, (unsigned int)cmp_buf,
  369.                sizeof(struct full_dirent));
  370.  
  371.       /* If this is the filename we are looking for, return
  372.          its starting cluster. */
  373.       if (!strncmp(cmp_buf, basename, name_len) &&
  374.           (ext_len == 0 || !strncmp(cmp_buf + 8, dot + 1, ext_len)))
  375.         return (unsigned int)_farnspeekw(*dirent_p + cluster_offset);
  376.  
  377.       /* This is not our file.  Search more, if more addresses left. */
  378.       dirent_p++;
  379.     }
  380.  
  381.   /* If not found, give up.  */
  382.   _djstat_fail_bits |= _STFAIL_BADSDA;
  383.   return 0;
  384. }
  385.  
  386. static char blanks_8[] = "        ";
  387.  
  388. static int
  389. stat_assist(const char *path, struct stat *statbuf)
  390. {
  391.   struct   ffblk ff_blk;
  392.   char     canon_path[MAX_TRUE_NAME];
  393.   short    drv_no;
  394.   unsigned dos_ftime;
  395.  
  396.   _djstat_fail_bits = 0;
  397.  
  398.   memset(statbuf, 0, sizeof(struct stat));
  399.   memset(&dos_ftime, 0, sizeof(dos_ftime));
  400.  
  401.   /* Fields which are constant under DOS.  */
  402.   statbuf->st_uid     = getuid();
  403.   statbuf->st_gid     = getgid();
  404.   statbuf->st_nlink   = 1;
  405. #ifndef  NO_ST_BLKSIZE
  406.   statbuf->st_blksize = _go32_info_block.size_of_transfer_buffer;
  407. #endif
  408.  
  409.   /* Get the drive number.
  410.      If no explicit drive, assume current drive.
  411.      This might fail, if the name is of the form \\machine\path
  412.      (which means, it's on a networked drive), but we don't
  413.      consider such names legal here.  In other words, DON'T call
  414.      stat() on a canonicalized name!  */
  415.   if (path[1] == ':')       /* explicit drive letter */
  416.     drv_no = toupper(*path) - 'A';
  417.   else
  418.     drv_no = __getdisk();
  419.  
  420.   /* Produce canonical pathname, with all the defaults resolved and
  421.      all redundant parts removed.  This calls undocumented DOS
  422.      function 60h.  */
  423.   if (_truename(path, canon_path))
  424.     {
  425.       /* Detect character device names which must be treated specially.
  426.          We could simply call FindFirst and test the 6th bit, but some
  427.          versions of DOS have trouble with this (see Ralph Brown's
  428.          Interrupt List, ``214E'', under `Bugs').  Instead we use
  429.          truename() which calls INT 21/AX=6000H.  For character devices
  430.          it returns X:/DEVNAME, where ``X'' is the current drive letter
  431.          (note the FORWARD slash!).  E.g., for CON or \dev\con it will
  432.          return C:/CON.
  433.          We will pretend that devices all reside on a special drive
  434.          called `@', which corresponds to st_dev = -1.  This is because
  435.          these devices have no files, and we must invent inode numbers
  436.          for them; this scheme allows to lower a risk of clash between
  437.          invented inode and one which belongs to a real file.  This is
  438.          also compatible with what our fstat() does.
  439.       */
  440.       if (canon_path[2] == '/')
  441.         {
  442.           char dev_name[9];     /* devices are at most 8 characters long */
  443.  
  444.           strncpy(dev_name, canon_path + 3, 8); /* the name without `X:/' */
  445.           dev_name[8] = '\0';
  446.           strcpy(canon_path, "@:\\dev\\");
  447.           strcat(canon_path, dev_name);
  448.           strncat(canon_path, blanks_8, 8 - strlen(dev_name)); /* blank-pad */
  449.           canon_path[15] = '\0';   /* ensure zero-termination */
  450.  
  451.           /* Invent inode */
  452.           statbuf->st_ino = _invent_inode(canon_path, 0, 0);
  453.  
  454.           /* Device code. */
  455.           statbuf->st_dev = -1;
  456. #ifdef  HAVE_ST_RDEV
  457.           statbuf->st_rdev = -1;
  458. #endif
  459.  
  460.           /* Set mode bits, including character special bit.
  461.              Should we treat printer devices as write-only?  */
  462.           statbuf->st_mode |= (S_IFCHR | READ_ACCESS | WRITE_ACCESS);
  463.  
  464.           /* We will arrange things so that devices have current time in
  465.              the access-time and modified-time fields of struct stat, and
  466.              zero (the beginning of times) in creation-time field.  This
  467.              is consistent with what DOS FindFirst function returns for
  468.              character device names (if it succeeds--see above).  */
  469.           statbuf->st_atime = statbuf->st_mtime = time(0);
  470.           statbuf->st_ctime = _file_time_stamp(dos_ftime);
  471.  
  472.           return 0;
  473.         }
  474.       else if (isalpha(canon_path[0]) &&
  475.                canon_path[1] == ':' && canon_path[2] == '\\')
  476.         {
  477.           /* _truename() returned a name with a drive letter.  (This is
  478.              always so for local drives, but some network redirectors
  479.              also do this.)  We will take this to be the TRUE drive
  480.              letter, because _truename() knows about SUBST and JOIN.
  481.              If the canonicalized path returns in the UNC form (which
  482.              means the drive is remote), it cannot be SUBSTed or JOINed,
  483.              because SUBST.EXE and JOIN.EXE won't let you do it; so, for
  484.              these cases, there is no problem in believing the drive
  485.              number we've got from the original path or from __getdisk().
  486.              Or is there?...  */
  487.           drv_no = toupper(canon_path[0]) - 'A';
  488.         }
  489.     }
  490.   else
  491.     {
  492.       /* _truename() failed.  (This really shouldn't happen, but who knows?)
  493.          At least uppercase all letters, convert forward slashes to backward
  494.          ones, and pray... */
  495.       register const char *src = path;
  496.       register       char *dst = canon_path;
  497.  
  498.       while ( (*dst = (*src > 'a' && *src < 'z'
  499.                        ? *src++ - ('a' - 'A')
  500.                        : *src++)) != '\0')
  501.         {
  502.           if (*dst == '/')
  503.             *dst = '\\';
  504.           dst++;
  505.         }
  506.  
  507.       _djstat_fail_bits |= _STFAIL_TRUENAME;
  508.     }
  509.  
  510.   /* Call DOS FindFirst function, which will bring us most of the info.
  511.      Note the use of PATH instead of CANON_PATH.  This is because
  512.      for networked drives _truename() changes the drive letter to a
  513.      redirector-specific string (called the UNC notation), which might
  514.      include the machine name, and several parent directories above the
  515.      root of our mounted filesystem.  E.g., under Novell we might have
  516.      \\MACHINE\ROOTDIR\OURDIR, where our tree on that drive starts with
  517.      OURDIR; Tsoft NFS (0.24Beta) gets us NFS.X:\OURDIR, where X is the
  518.      original drive letter; other redirectors will probably do their
  519.      weird things.  This could totally confuse FindFirst; it is safer
  520.      just to use PATH.
  521.    */
  522.   if (!__findfirst(path, &ff_blk, ALL_FILES))
  523.     {
  524.       /* Time fields. */
  525.       dos_ftime =
  526.         ( (unsigned short)ff_blk.ff_fdate << 16 ) +
  527.           (unsigned short)ff_blk.ff_ftime;
  528.  
  529.       if ( (_djstat_flags & _STAT_INODE) == 0 )
  530.         {
  531.  
  532.           /* For networked drives, don't believe the starting cluster
  533.              that the network redirector feeds us; always invent inode.
  534.              This is because network redirectors leave bogus values there,
  535.              and we don't have enough info to decide if the starting
  536.              cluster value is real or just a left-over from previous call.
  537.              For local files, try first using DOS SDA to get the inode from
  538.              the file's starting cluster number; if that fails, invent inode.
  539.              Note that the if clause below tests for non-zero value returned
  540.              by is_remote_drive(), which includes possible failure (-1).
  541.              This is because findfirst() already succeeded for our pathname,
  542.              and therefore the drive is a legal one; the only possibility that
  543.              is_remote_drive() fails is that some network redirector takes
  544.              over IOCTL functions in an incompatible way, which means the
  545.              drive is remote.  QED.  */
  546.           if (_is_remote_drive(drv_no) ||
  547.               (statbuf->st_ino = get_inode_from_sda(ff_blk.ff_name)) == 0)
  548.             {
  549.               _djstat_fail_bits |= _STFAIL_HASH;
  550.               statbuf->st_ino =
  551.                 _invent_inode(canon_path, dos_ftime, ff_blk.ff_fsize);
  552.             }
  553.         }
  554.  
  555.       /* File size. */
  556.       statbuf->st_size = ff_blk.ff_fsize;
  557.  
  558.       /* Mode bits. */
  559.       statbuf->st_mode |= READ_ACCESS;
  560.       if ( !(ff_blk.ff_attrib & 0x07) )  /* no R, H or S bits set */
  561.         statbuf->st_mode |= WRITE_ACCESS;
  562.  
  563.       /* Directories should have Execute bits set. */
  564.       if (ff_blk.ff_attrib & 0x10)
  565.         statbuf->st_mode |= (S_IFDIR | EXEC_ACCESS);
  566.  
  567.       else
  568.         {
  569.           /* This is a regular file. */
  570.           char *extension  = strrchr(ff_blk.ff_name, '.');
  571.  
  572.           /* Set regular file bit.  */
  573.           statbuf->st_mode |= S_IFREG;
  574.  
  575.           if ( (_djstat_flags & _STAT_EXECBIT) == 0 )
  576.             {
  577.               /* Set execute bits based on file's extension and
  578.                  first 2 bytes. */
  579.               if (extension)
  580.                 extension++;    /* get past the dot */
  581.               if (_is_executable(path, -1, extension))
  582.                 statbuf->st_mode |= EXEC_ACCESS;
  583.             }
  584.         }
  585.     }
  586.  
  587. #ifdef  S_IFLABEL
  588.   /* Check for volume label on local drives.  Net drives may not support
  589.      this properly. */
  590.   else if (!_is_remote_drive(drv_no) && !__findfirst(path, &ff_blk, FA_LABEL))
  591.     {
  592.       statbuf->st_mode = READ_ACCESS | S_IFLABEL;
  593.       statbuf->st_ino = 1;
  594.       statbuf->st_size = 0;
  595.       dos_ftime = ( (unsigned)ff_blk.ff_fdate << 16 ) + ff_blk.ff_ftime;
  596.     }
  597. #endif
  598.  
  599.   /* Detect root directories.  These are special because, unlike
  600.      subdirectories, FindFirst fails for them.  If you think the
  601.      simple test of the string returned by _truename() to have
  602.      ":\\" at its end will suffice, think again.  A network
  603.      redirector could tweak what _truename() returns to be
  604.      utterly unrecognizable as root directory.  */
  605.   else
  606.     {
  607.       static char root_dir_pat[] = " :\\";
  608.       char root_dir[sizeof(root_dir_pat)];
  609.  
  610.       /* Construct "X:\", where X is the drive letter. */
  611.       strcpy(root_dir, root_dir_pat);
  612.       root_dir[0] = drv_no + 'A';
  613.  
  614.       if (strcmp(canon_path + 1, ":\\"))
  615.         {
  616.  
  617.           /* The simple test of having "X:\" in canonical pathname
  618.              failed.  Feed _truename() with root directory on that
  619.              drive and see if it returns identical to our CANON_PATH.  */
  620.           char root_path[MAX_TRUE_NAME];
  621.           char *p;
  622.  
  623.           if (!(p = _truename(root_dir, root_path)) || strcmp(p, canon_path))
  624.             {
  625.               /* The root is different, or the drive is inaccessible.
  626.                  This must be a non-existing file/directory.  */
  627.               errno = ENOENT;   /* FindFirst sets it to ENMFILE */
  628.               return -1;
  629.             }
  630.         }
  631.  
  632.       /* Still here, so this is root directory.  Assemble the information
  633.          for stat_buf.  */
  634.  
  635.       /* Mode bits. */
  636.       statbuf->st_mode |= (S_IFDIR | READ_ACCESS | WRITE_ACCESS | EXEC_ACCESS);
  637.  
  638.       /* Root directory will have an inode = 1.  Valid cluster numbers
  639.          for real files under DOS start with 2. */
  640.       statbuf->st_ino = 1;
  641.  
  642.       /* Simulate zero size.  This is what FindFirst returns for every
  643.          sub-directory.  Later we might compute a better approximation
  644.          (see below).  */
  645.       ff_blk.ff_fsize = 0L;
  646.  
  647.       /* The time fields are left to be zero, unless the user wants us
  648.          to try harder.  In the latter case, we check if the root has
  649.          a volume label entry, and use its time if it has. */
  650.  
  651.       if ( (_djstat_flags & _STAT_ROOT_TIME) == 0 )
  652.         {
  653.           char buf[7];
  654.  
  655.           strcpy(buf, root_dir);
  656.           strcat(buf, "*.*");
  657.           if (!__findfirst(buf, &ff_blk, FA_LABEL))
  658.             dos_ftime = ( (unsigned)ff_blk.ff_fdate << 16 ) + ff_blk.ff_ftime;
  659.           else
  660.             _djstat_fail_bits |= _STFAIL_LABEL;
  661.         }
  662.               
  663.     }
  664.  
  665.   /* Device code. */
  666.   statbuf->st_dev = drv_no;
  667. #ifdef  HAVE_ST_RDEV
  668.   statbuf->st_rdev = drv_no;
  669. #endif
  670.  
  671.   /* Time fields. */
  672.   statbuf->st_atime = statbuf->st_mtime = statbuf->st_ctime =
  673.     _file_time_stamp(dos_ftime);
  674.  
  675.   if ( ! strcmp(ff_blk.lfn_magic,"LFN32") )
  676.     {
  677.       unsigned xtime;
  678.       xtime = *(unsigned *)&ff_blk.lfn_ctime;
  679.       if(xtime)            /* May be zero if file written w/o lfn active */
  680.         statbuf->st_ctime = _file_time_stamp(xtime);
  681.       xtime = *(unsigned *)&ff_blk.lfn_atime;
  682.       if(xtime > dos_ftime)    /* Accessed time is date only, no time */
  683.         statbuf->st_atime = _file_time_stamp(xtime);
  684.     }
  685.  
  686.   if ( (statbuf->st_mode & S_IFMT) == S_IFDIR && statbuf->st_size == 0 &&
  687.        (_djstat_flags & _STAT_DIRSIZE) == 0 )
  688.     {
  689.       /* Under DOS, directory entries for subdirectories have
  690.          zero size.  Therefore, FindFirst brings us zero size
  691.          when called on a directory.  (Some network redirectors
  692.          might do a better job, thus above we also test for zero size
  693.          actually being returned.)  If we have zero-size directory,
  694.          we compute here the actual directory size by reading its
  695.          entries, then multiply their number by 32 (the size of a
  696.          directory entry under DOS).  This might lose in the case
  697.          that many files were deleted from a once huge directory,
  698.          because AFAIK, directories don't return unused clusters to
  699.          the disk pool.  Still, it is a good approximation of the
  700.          actual directory size.
  701.  
  702.          The (max) size of the root directory could also be taken from
  703.          the disk BIOS Parameter Block (BPB) which can be obtained
  704.          by calling IOCTL (INT 21/AH=44H), subfunction 0DH, minor
  705.          function 60H.  But we will treat all directories the same,
  706.          even at performance cost, because it's more robust for
  707.          networked drives.  */
  708.  
  709.       size_t pathlen = strlen(path);
  710.       char   lastc   = path[pathlen - 1];
  711.       char  *search_spec = (char *)alloca(pathlen + 10); /* need only +5 */
  712.       int i = 0;
  713.  
  714.       strcpy(search_spec, path);
  715.       if (lastc == '/' || lastc == '\\' || lastc == ':')
  716.         strcat(search_spec, "*.*");
  717.       else
  718.         strcat(search_spec, "\\*.*");
  719.  
  720.       if (!__findfirst(search_spec, &ff_blk, ALL_FILES))
  721.         for (i = 1; !__findnext(&ff_blk); ++i)
  722.           ;
  723.  
  724.       /* In non-root directories, don't count the ``.'' and ``..''
  725.          entries, so that empty directories will be shown as such.  */
  726.       if (statbuf->st_ino != 1)
  727.         i -= 2;
  728.  
  729.       statbuf->st_size = i * sizeof(struct full_dirent);
  730.     }
  731.  
  732.   return 0;
  733. }
  734.  
  735. /* Main entry point.  This is library stat() function.
  736.  */
  737.  
  738. int
  739. stat(const char *path, struct stat *statbuf)
  740. {
  741.   int            e = errno;
  742.   char pathname[MAX_TRUE_NAME], *p;
  743.  
  744.   if (!path || !statbuf)
  745.     {
  746.       errno = EFAULT;
  747.       return -1;
  748.     }
  749.  
  750.   strcpy(pathname, path);
  751.   p = pathname + strlen(pathname) - 1;
  752.   /* Get rid of trailing slash.  It confuses FindFirst and also causes
  753.      the inode-inventing mechanism think d:/path/ and d:/path are
  754.      different, because _truename() retains one trailing slash.  But
  755.      leave alone a trailing slash if it's a root directory, like in
  756.      "/" or "d:/" */
  757.   while (p > pathname && p[-1] != ':' && (*p == '/' || *p == '\\'))
  758.     *p-- = '\0';
  759.  
  760.   /* Under DOS it is customary to use "X:" for the CURRENT directory
  761.      of drive X.  But FindFirst doesn't like this, so we convert it
  762.      to "X:." which works.  This eliminates multiple #ifdef's in
  763.      many Unix-born programs.  */
  764.   if (*p++ == ':')
  765.     {
  766.       *p++ = '.';
  767.       *p   = '\0';
  768.     }
  769.   if (stat_assist(pathname, statbuf) == -1)
  770.     {
  771.       return -1;      /* errno set by stat_assist() */
  772.     }
  773.   else
  774.     {
  775.       errno = e;
  776.       return 0;
  777.     }
  778. }
  779.  
  780. #ifdef  TEST
  781.  
  782. unsigned short _djstat_flags = 0;
  783.  
  784. void
  785. main(int argc, char *argv[])
  786. {
  787.   struct stat stat_buf;
  788.   char *endp;
  789.  
  790.   if (argc < 2)
  791.     {
  792.       fprintf (stderr, "Usage: %s <_djstat_flags> <file...>\n", argv[0]);
  793.       exit(0);
  794.     }
  795.  
  796.   stat(*argv, &stat_buf);
  797.   fprintf(stderr, "DOS %d.%d (%s)\n", _osmajor, _osminor, _os_flavor);
  798.   argc--; argv++;
  799.  
  800.   _djstat_flags = (unsigned short)strtoul(*argv, &endp, 0);
  801.   argc--; argv++;
  802.  
  803.   while (argc--)
  804.     {
  805.       if (!stat(*argv, &stat_buf))
  806.         {
  807.           fprintf(stderr, "%s: %d %6u %o %d %d %ld %lu %s", *argv,
  808.                   stat_buf.st_dev,
  809.                   (unsigned)stat_buf.st_ino,
  810.                   stat_buf.st_mode,
  811.                   stat_buf.st_nlink,
  812.                   stat_buf.st_uid,
  813.                   (long)stat_buf.st_size,
  814.                   (unsigned long)stat_buf.st_mtime,
  815.                   ctime(&stat_buf.st_mtime));
  816.           _djstat_describe_lossage(stderr);
  817.         }
  818.       else
  819.         {
  820.           fprintf(stderr, "%s: lossage", *argv);
  821.           perror(" ");
  822.           _djstat_describe_lossage(stderr);
  823.         }
  824.  
  825.       ++argv;
  826.     }
  827.  
  828.     exit (0);
  829. }
  830.  
  831. #endif
  832.